package com.example.audio_test.ui

import android.Manifest
import android.os.Environment
import android.view.SurfaceHolder
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.audio_test.R
import com.example.audio_test.utils.AudioMediaCodecWorker
import com.example.audio_test.utils.VideoMediaCodecWorker
import com.kun.base.ui.AbsBaseActivity
import kotlinx.android.synthetic.main.activity_video_play.*
import permissions.dispatcher.NeedsPermission
import permissions.dispatcher.RuntimePermissions
import java.io.File

/**
 *视频画面播放
 *
 * @author : Kun
 * @date : 2021/6/24
 * @time : 11:45
 */
@RuntimePermissions
@Route(path = "/recordTest/VideoPlayActivity")
class VideoPlayActivity : AbsBaseActivity(), SurfaceHolder.Callback {

    private var videoMediaCodecWorker: VideoMediaCodecWorker? = null
    private var audioMediaCodecWorker: AudioMediaCodecWorker? = null

    override fun getLayoutId(): Int {
        return R.layout.activity_video_play
    }

    override fun initViewModel() {
    }

    override fun initView() {
        btn_play.setOnClickListener {
            playVideoWithPermissionCheck()
        }
        play_surfaceView.holder.addCallback(this)
    }

    override fun surfaceCreated(holder: SurfaceHolder) {
        //  /storage/emulated/0/Android/data/com.example.myapplication/files/Movies/test.h264
        //
        val file = File(getExternalFilesDir(Environment.DIRECTORY_MOVIES), "test.mp4")

//        val path = "/storage/emulated/0/DCIM/Camera/VID_20210215_165553.mp4"
        if (videoMediaCodecWorker == null) {
            videoMediaCodecWorker = VideoMediaCodecWorker(
                holder.surface,
                file.absolutePath
            )
        }
        if (audioMediaCodecWorker == null) {
            audioMediaCodecWorker = AudioMediaCodecWorker(file.absolutePath)
        }
    }

    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
    }

    override fun surfaceDestroyed(holder: SurfaceHolder) {
//        videoMediaCodecWorker!!.interrupt()
        videoMediaCodecWorker!!.stopPlay()
        audioMediaCodecWorker!!.stopPlay()
    }

    @NeedsPermission(
        Manifest.permission.READ_EXTERNAL_STORAGE
    )
    fun playVideo() {
        videoMediaCodecWorker!!.start()
        audioMediaCodecWorker!!.start()
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        onRequestPermissionsResult(requestCode, grantResults)
    }
}